package com.example.chuntiao.cophook.ui;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.view.ActionMode;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;

import com.example.chuntiao.cophook.R;
import com.example.chuntiao.cophook.adapter.CompPerson;
import com.example.chuntiao.cophook.adapter.PersonAdapter;
import com.example.chuntiao.cophook.beans.Person;
import com.example.chuntiao.cophook.beans.PersonDataSupport;
import com.example.chuntiao.cophook.beans.PersonHideDataSupport;
import com.example.chuntiao.cophook.mytools.ArrPolisher;
import com.example.chuntiao.cophook.mytools.HttpTool;
import com.example.chuntiao.cophook.mytools.PhoneTool;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class OrgDetail extends BaseActivity {
    String oid;
    RecyclerView recycPeople;
    PersonAdapter mAdapter;
    ActionMode actionMode;
    HashSet<View> viewsToHide;
    Toolbar toolbar;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();

        oid = intent.getStringExtra("oid");
        setTitle(intent.getStringExtra("oname"));
        String intro = intent.getStringExtra("intro");
        int orgImgVer = intent.getIntExtra("img_ver", -1);

        setContentView(R.layout.activity_one_rec_basic);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        recycPeople = (RecyclerView) findViewById(R.id.rec_list);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recycPeople.setLayoutManager(layoutManager);
        mAdapter = new PersonAdapter(true, oid, intro, orgImgVer);
        recycPeople.setAdapter(mAdapter);


        mAdapter.setOnClickListener(new PersonAdapter.OnclickListener() {
            @Override
            public void OnNormalBodyLongClick(View v, final int position) {
                viewsToHide = new HashSet<View>();

                v.setBackgroundColor(ContextCompat.getColor(OrgDetail.this, R.color.deep_gray));//长按先选中来源
                viewsToHide.add(v);


                if (actionMode == null) {
                    OrgDetail.this.startSupportActionMode(new ActionMode.Callback() {
                        @Override
                        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
                            if (actionMode == null) {
                                actionMode = mode;
                                MenuInflater inflater = mode.getMenuInflater();
                                inflater.inflate(R.menu.menu_action_mode, menu);
                                return true;
                            } else {
                                return false;
                            }
                        }

                        @Override
                        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
                            return false;
                        }

                        @Override
                        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
                            switch (item.getItemId()) {
                                case R.id.action_hide:
                                    if (viewsToHide.size() == 0)
                                        break;
                                    for (View v : viewsToHide) {

                                        int index = mAdapter.getmPersonList().indexOf(new Person((String) v.getTag(R.id.uid)));
                                        Person p = mAdapter.getmPersonList().get(index);
                                        PersonHideDataSupport peronToHide = new PersonHideDataSupport(p);

                                        peronToHide.save();//数据存储至‘隐藏表’
                                        DataSupport.deleteAll(PersonDataSupport.class, "uid = ? ", p.getUid());//普通表中删除

                                        mAdapter.getmPersonList().remove(index);
                                        mAdapter.notifyItemRemoved((Integer) v.getTag(R.id.position));//请特别注意此处的位置
                                        v.setBackgroundColor(ContextCompat.getColor(OrgDetail.this, R.color.no_color));//啊我发现当 ｖ 被 mAdapter 移除后并没有销毁，所以可能有颜色残留，太不爽，只好记着把颜色还原
                                    }
                                    mAdapter.notifyItemRangeChanged(0, mAdapter.getmPersonList().size() + 1);
                                    viewsToHide.clear();
                                    break;
                                case R.id.action_reset:
                                    for (View v : viewsToHide) {
                                        v.setBackgroundColor(ContextCompat.getColor(OrgDetail.this, R.color.no_color));
                                    }
                                    viewsToHide.clear();
                                    break;

                                case R.id.action_export:
                                    ArrayList<Person> persons = new ArrayList<Person>();
                                    for (View v : viewsToHide) {
                                        int index = mAdapter.getmPersonList().indexOf(new Person((String) v.getTag(R.id.uid)));
                                        Person p = mAdapter.getmPersonList().get(index);
                                        persons.add(p);
                                        v.setBackgroundColor(ContextCompat.getColor(OrgDetail.this, R.color.no_color));
                                    }
                                    OrgDetailPermissionsDispatcher.writeToPhoneWithCheck(OrgDetail.this, (List<Person>) persons.clone());
                                    persons.clear();
                                    viewsToHide.clear();
                                    actionMode.finish();
                                    break;
                            }
                            return true;
                        }

                        @Override
                        public void onDestroyActionMode(ActionMode mode) {

                            for (View v : viewsToHide) {
                                v.setBackgroundColor(ContextCompat.getColor(OrgDetail.this, R.color.no_color));
                            }
                            viewsToHide.clear();
                            viewsToHide = null;
                            actionMode = null;
                        }
                    });
                }
            }

            @Override
            public void OnNormalBodyClick(View v, int position) {

                if (actionMode == null) {
                    Intent intent = new Intent(OrgDetail.this, PersonDetailActivity.class);
                    int index = mAdapter.getmPersonList().indexOf(new Person((String) v.getTag(R.id.uid)));
                    intent.putExtra("uname", mAdapter.getmPersonList().get(index).getName());
                    intent.putExtra("phone1", mAdapter.getmPersonList().get(index).getPhone1());
                    intent.putExtra("phone2", mAdapter.getmPersonList().get(index).getPhone2());
                    intent.putExtra("locate", mAdapter.getmPersonList().get(index).getLocate());
                    intent.putExtra("img_ver", mAdapter.getmPersonList().get(index).getImgVer());
                    intent.putExtra("uid", mAdapter.getmPersonList().get(index).getUid());

                    startActivityForResult(intent, MainActivity.REQ_FOR_PERSONDETAIL_ACTI);

                } else {
                    if (viewsToHide.contains(v)) {
                        v.setBackgroundColor(ContextCompat.getColor(OrgDetail.this, R.color.no_color));
                        viewsToHide.remove(v);
                    } else {
                        v.setBackgroundColor(ContextCompat.getColor(OrgDetail.this, R.color.deep_gray));
                        viewsToHide.add(v);
                    }
                }
            }

            @Override
            public void OnNormalPhoneClick(View v, int position) {
                //int index = mAdapter.getmPersonList().indexOf(new Person((String) v.getTag(R.id.uid)));
                if (actionMode == null)
                    if (ContextCompat.checkSelfPermission(OrgDetail.this, Manifest.permission.CALL_PHONE)
                            != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(OrgDetail.this, new String[]{Manifest.permission.CALL_PHONE}, PersonDetailActivity.REQ_PERMIT_FOR_CALL);
                    } else {
                        PhoneTool.call(mAdapter.getmPersonList().get(position-1).getPhone1(), OrgDetail.this);
                    }
            }
        });

    }


    @Override
    protected void onResume() {
        super.onResume();
        new LoadDataTask().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_org_detail, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;

            case R.id.share_org:
                Intent intent = new Intent(OrgDetail.this, CreateScanCode.class);
                intent.putExtra("oid", oid);
                startActivity(intent);
                break;

            case R.id.menu_quit_org:
                final ProgressDialog progressDialog = ProgressDialog.show(OrgDetail.this, "请稍候", "正在退出");
                new AsyncTask<Void, Void, Boolean>() {

                    AlertDialog alertDialog = null;

                    @Override
                    protected void onPreExecute() {
                        alertDialog = new AlertDialog.Builder(OrgDetail.this)
                                .setMessage("退出组织失败")
                                .setPositiveButton(R.string.yse, null)
                                .create();

                    }

                    @Override
                    protected Boolean doInBackground(Void... params) {
                        String resultStr = null;
                        try {
                            resultStr = HttpTool.sendOkHttpRequest(OrgDetail.this, HttpTool.CODE_QIUTE_ORG, oid);
                        } catch (ConnectException e) {
                            alertDialog.setMessage("联网失败，请检查网络");
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if (resultStr != null && resultStr.equals("quited"))
                            return true;

                        return false;
                    }

                    @Override
                    protected void onPostExecute(Boolean result) {
                        progressDialog.dismiss();
                        if (result) {
                            alertDialog = null;
                            setResult(RESULT_OK);
                            finish();
                        } else
                            alertDialog.show();

                    }
                }.execute();
                break;
        }
        return true;
    }

    class LoadDataTask extends AsyncTask<String, Void, ArrayList<Person>> {

        LoadDataTask() {
            super();
        }

        void readFromLocal(ArrayList<Person> empList, String oid) {

            Cursor cursor = DataSupport.findBySQL("select * from PersonDataSupport where uid in " +
                    "(select uid from ChoiceDataSupport where oid=?)", oid);

            while (cursor.moveToNext()) {
                Person p = new Person();
                p.setUid(cursor.getString(cursor.getColumnIndex("uid")));
                p.setLocate(cursor.getString(cursor.getColumnIndex("locate")));
                p.setPhone1(cursor.getString(cursor.getColumnIndex("phone1")));
                p.setPhone2(cursor.getString(cursor.getColumnIndex("phone2")));
                p.setName(cursor.getString(cursor.getColumnIndex("name")));
                p.setImgVer(cursor.getInt(cursor.getColumnIndex("imgver")));

                empList.add(p);
            }
            cursor.close();

        }

        @Override
        protected ArrayList<Person> doInBackground(String... params) {
            ArrayList<Person> results = new ArrayList<Person>();
            readFromLocal(results, oid);
            ArrPolisher.polish(results);
            Collections.sort(results, new CompPerson());
            {
                Person p = new Person();
                p.setPyOfHomeName("#");
                results.add(p);
            }

            return results;
        }

        @Override
        protected void onPostExecute(ArrayList<Person> persons) {

            mAdapter.setmPersonList(persons);
            mAdapter.notifyDataSetChanged();
        }
    }

    @NeedsPermission(Manifest.permission.WRITE_CONTACTS)
    void writeToPhone(final List<Person> persons) {

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                ContentValues values = new ContentValues();
                ContentResolver contentResolver = getContentResolver();

                for (Person p : persons) {
                    values.clear();
                    Uri rawContactUri = getContentResolver().
                            insert(ContactsContract.RawContacts.CONTENT_URI, values);

                    long rawContactId = ContentUris.parseId(rawContactUri);

                    if (p.getName() != "") {
                        values.clear();
                        values.put(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, rawContactId);
                        values.put(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
                        values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, p.getName());
                        contentResolver.insert(ContactsContract.Data.CONTENT_URI,
                                values);
                    }

                    // 向data表插入电话数据
                    if (p.getPhone1() != "") {
                        values.clear();
                        values.put(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, rawContactId);
                        values.put(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, p.getPhone1());
                        values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
                        contentResolver.insert(ContactsContract.Data.CONTENT_URI,
                                values);
                    }
                    // 向data表插入电话数据
                    if (p.getPhone2() != "") {
                        values.clear();
                        values.put(ContactsContract.RawContacts.Data.RAW_CONTACT_ID, rawContactId);
                        values.put(ContactsContract.RawContacts.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
                        values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, p.getPhone2());
                        values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_HOME);
                        contentResolver.insert(ContactsContract.Data.CONTENT_URI,
                                values);
                    }
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                Snackbar.make(recycPeople, "导出完成", Snackbar.LENGTH_SHORT).show();
            }
        }.execute();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        OrgDetailPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale(Manifest.permission.WRITE_CONTACTS)
    void showRationWrite(final PermissionRequest request) {
        new AlertDialog.Builder(OrgDetail.this)
                .setMessage("需要你授权来写入系统通讯录")
                .setPositiveButton("去授权", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("朕拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .show();
    }
}
